package top.chenfu.blog.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import top.chenfu.blog.dao.UserMapper;
import top.chenfu.blog.entity.Role;
import top.chenfu.blog.entity.User;
import top.chenfu.blog.service.UserService;

import java.util.List;
import java.util.Objects;

/**
 * @Auther chenfu
 * @2019/10/30 15:05
 * @Desc
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.selectOneByUsername(username);
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("用户不存在");
        }
        List<Role> roles = userMapper.selectRolesByUserId(user.getId());
        user.setRoles(roles);
        return user;
    }

    @Override
    public int updateUserEmail(String email) {
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        principal.setEmail(email);
        return userMapper.updateByPrimaryKeySelective(principal);
    }

}
